from flask import Flask, request
from time import time
from datetime import datetime
from json import dumps, loads
from os import path
from csv import writer
from lib import cloud_password_verify_api as cpv_api
app = Flask(__name__)

file_dir = path.dirname(__file__)
with open(f'{file_dir}/html/index.html', 'r', encoding='utf8') as index_file:
    index_html = index_file.read()
with open(f'{file_dir}/html/items.html', 'r', encoding='utf8') as items_file:
    items_html = items_file.read()
with open(f'{file_dir}/html/verify.html', 'r', encoding='utf8') as verify_file:
    verify_html = verify_file.read()

number = 0

@app.route("/")
def index():
    return verify_html


@app.route("/cpv_api", methods=['GET', 'POST'])
def cpv_api_lib():
    method = request.method
    usrname = request.form.get('usrname', str)
    password = request.form.get('password', str)
    print((usrname, password))
    if method == 'GET':
        return verify_html
    elif method == 'POST':
        api_key = 'sk_340447e47df1812a0fc1b7d109094d114b370cbb3f93e3234eca4fc97f34aa40'
        password = str((usrname, password))
        if cpv_api.verify(api_key, password) == False:
            return items_html
        else:
            return 'the usrname or password is incorrect.'


'''
@app.route("/items")
def items():
    global number
    number = request.args.get("number")
    return items_html
'''

@app.route("/logged",  methods=['GET', 'POST'])
def logged():
    global number
    stu_list = request.form.getlist('number')
    talk_list = request.form.getlist('talk')
    discipline_list = request.form.getlist('discipline')
    for stu in stu_list:
        n = 0
        for j in talk_list:
            n += int(j)
        for k in discipline_list:
            n += int(k)
        with open(f'/{file_dir}/json_database.json', 'r') as json_file:
            json_db = json_file.read()
        json_db = loads(json_db)
        point = json_db[stu]
        point = int(point)
        point += n
        point = str(point)
        json_db[stu] = point
        with open(f'/{file_dir}/json_database.json', 'w') as json_file:
            json_file.write(dumps(json_db))

        log_list = [stu, talk_list, discipline_list]
        with open(f'/{file_dir}/operate_log.csv', 'a') as csv_file:
            csv_file.write(str(log_list))


    #用number对应form计算分值，整到json上
    
    #记录转好格式整成csv
    return str(n)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8091, debug=True)